package com.niiwoo.civet.trade.service.local.contract;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.dto.response.UserIdentityInfoResponseDTO;
import com.niiwoo.civet.user.enums.OrganizationEnum;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.civet.user.service.UserAuthorizationInfoDubboService;
import com.niiwoo.civet.user.service.UserIdentityDubboService;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO.DynamicTable;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;

/**
 * 反担保合同
 * 
 * @author liaojunjun
 *
 */
@Service
public class AntiGuaranteeContract extends AbstractFadadaContract {
	
	private static final Logger logger = LoggerFactory.getLogger(AntiGuaranteeContract.class);

	@Autowired
	private SnowflakeIdWorker snowflakeIdWorker;

	@Reference(version = "1.0.0")
	private UserIdentityDubboService userIdentityDubboService;

	@Reference(version = "1.0.0")
	private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;

	@Reference(version = "1.0.0")
	private OrganizationDubboService organizationDubboService;

	@Override
	public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
										   Project project, String userId) throws Exception{
		logger.info("反担保合同处理开始... projectId:{}", project.getProjectId());
		String contractId = snowflakeIdWorker.nextId() + "";

		List<SimpleOrgInfo> simpleOrgInfoList = organizationDubboService.getGuaranteeAndAntiGuaranteeInfo();
		SimpleOrgInfo guarantee = null;
		SimpleOrgInfo antiGuarantee = null;
		for (SimpleOrgInfo simpleOrgInfo : simpleOrgInfoList) {
			if (OrganizationEnum.GUARANTEE_ORG.getType().equals(simpleOrgInfo.getType())) {
				guarantee = simpleOrgInfo;
			} else if (OrganizationEnum.ANTI_GUARANTEE_ORG.getType().equals(simpleOrgInfo.getType())) {
				antiGuarantee = simpleOrgInfo;
			}
		}

		UserIdentityInfoResponseDTO borrower = userIdentityDubboService.get(project.getBorrowUserId());

		this.generateContract(contractTemplate, contractId, bizContractNo, borrower, guarantee, antiGuarantee);

		ProjectContract result = this.signContract(contractTemplate, contractId, project, borrower, guarantee,
				antiGuarantee);

		this.contractFilling(contractId);
		logger.info("反担保合同处理结束... projectId:{}", project.getProjectId());
		return result;

	}

	private void generateContract(FadadaContractTemplateFile contractTemplate, String contractId, String bizContractNo,
			UserIdentityInfoResponseDTO borrower, SimpleOrgInfo guarantee, SimpleOrgInfo antiGuarantee) throws Exception{
		logger.info("反担保合同生成开始...");
		GenerateContractRequestDTO dto = new GenerateContractRequestDTO();

		dto.setContractId(contractId);
		dto.setDocTitle(contractTemplate.getTemplateName());
		dto.setTemplateId(contractTemplate.getTemplateId());

		Map<String, String> parameterMap = new HashMap<String, String>();

		parameterMap.put("antiGuarantee", antiGuarantee.getOrganizationName());
		parameterMap.put("antiGuaranteeRepresentative", antiGuarantee.getRepresentative());
		parameterMap.put("antiGuaranteeAddress", antiGuarantee.getAddress());
		parameterMap.put("antiGuaranteePhoneNo", antiGuarantee.getLegalPersonPhoneNumber());
		parameterMap.put("antiGuaranteeEmail", antiGuarantee.getEmail());

		parameterMap.put("guarantee", guarantee.getOrganizationName());
		parameterMap.put("guaranteeRepresentative", guarantee.getRepresentative());
		parameterMap.put("guaranteeAddress", guarantee.getAddress());

		parameterMap.put("borrowerName", borrower.getName());
		parameterMap.put("borrowerIdentityCard", borrower.getIdCard());

		parameterMap.put("contractNo", bizContractNo);

		parameterMap.put("signDate", DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));

		dto.setParameterMap(parameterMap);

		// 签章列表
		List<List<String>> signatureNamesList = new ArrayList<>();

		// 签章信息
		String antiGuaranteeSignatureNamesText = "                甲方（签章）：" + antiGuarantee.getOrganizationName();
		List<String> antiGuaranteeSignatureNamesCells = new ArrayList<>();
		antiGuaranteeSignatureNamesCells.add(antiGuaranteeSignatureNamesText);
		signatureNamesList.add(antiGuaranteeSignatureNamesCells);

		// 签章信息
		String guaranteeSignatureNamesText = "                乙方（签章）：" + guarantee.getOrganizationName();
		List<String> guaranteeSignatureNamesCells = new ArrayList<>();
		guaranteeSignatureNamesCells.add(guaranteeSignatureNamesText);
		signatureNamesList.add(guaranteeSignatureNamesCells);

		// 签章信息
		String borrowerSignatureNamesText = "                丙方（签章）：" + borrower.getName();
		List<String> borrowerSignatureNamesCells = new ArrayList<>();
		borrowerSignatureNamesCells.add(borrowerSignatureNamesText);
		signatureNamesList.add(borrowerSignatureNamesCells);

		List<String> headers = new ArrayList<>();
		headers.add("");
		// 所有人签名 在pdf合同模板的keyword下面插入(正好在页尾，不用留空白)，需要留够空白，不然会覆盖下面的内容
		DynamicTable signNameTable = new DynamicTable();
		signNameTable.setInsertWay(1);
		signNameTable.setKeyword("仲裁裁决是终局的，对各方均有约束力。");
		signNameTable.setCellHeight(60f);
		signNameTable.setHeaders(headers);
		// 签名时需要增加高度并居中显示
		signNameTable.setCellVerticalAlignment(5);
		signNameTable.setDatas(signatureNamesList);
		signNameTable.setBorderFlag(false);
		List<DynamicTable> tables = new ArrayList<DynamicTable>();
		tables.add(signNameTable);

		dto.setDynamicTables(tables);

		generateContract(dto);
		logger.info("反担保合同生成结束...");
	}

	private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, String contractId,
			Project project, UserIdentityInfoResponseDTO borrower, SimpleOrgInfo guarantee, SimpleOrgInfo antiGuarantee) throws Exception{
		String METHOD_NAME = "法大大合同自动签署-反担保合同 projectId:" + project.getProjectId();
		logger.info(METHOD_NAME);
		String docTitle = borrower.getName() + "的反担保合同_" + contractId;

		// 反担保公司签署
		String transactionId = snowflakeIdWorker.nextId() + "";
		String antiGuaranteeCaCertId = antiGuarantee.getFadadaCacertId();
		String antiGuaranteeSignKeyword = "甲方（签章）：" + antiGuarantee.getOrganizationName();
		FadadaResponseDTO fadadaResponse = extSignAuto(transactionId, contractId, antiGuaranteeCaCertId,
				SignClientRoleEnum.GUARANTEE.getValue(), docTitle, antiGuaranteeSignKeyword);
		logger.info("法大大合同自动签署-反担保合同 反担保公司签署结束... projectId:{}", project.getProjectId());
		// 担保公司签署
		transactionId = snowflakeIdWorker.nextId() + "";
		String guaranteeCaCertId = guarantee.getFadadaCacertId();
		String guaranteeSignKeyword = "乙方（签章）：" + guarantee.getOrganizationName();
		fadadaResponse = extSignAuto(transactionId, contractId, guaranteeCaCertId,
				SignClientRoleEnum.GUARANTEE.getValue(), docTitle, guaranteeSignKeyword);
		logger.info("法大大合同自动签署-反担保合同 担保公司签署结束... projectId:{}", project.getProjectId());
		// 借款人签署
		transactionId = snowflakeIdWorker.nextId() + "";
		String borrowerCaCertId = userAuthorizationInfoDubboService.getUserAuthorizationInfo(borrower.getUserId())
				.getFadadaCacertId();
		String borrowerSignKeyword = "丙方（签章）：" + borrower.getName();
		fadadaResponse = extSignAuto(transactionId, contractId, borrowerCaCertId,
				SignClientRoleEnum.BORROWER.getValue(), docTitle, borrowerSignKeyword);
		logger.info("法大大合同自动签署-反担保合同 借款人签署结束... projectId:{}", project.getProjectId());
		return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), contractId, transactionId,
				fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
	}

}
